package controllers

import (
	"time"

	"github.com/gofiber/fiber/v2"
	"gorm.io/gorm"

	"main/src/models"
	"main/src/utils"
)

func LoginHandler(c *fiber.Ctx) error {
	var user models.User

	db := c.Locals("db")
	if err := c.BodyParser(&user); err != nil {
		return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "Invalid request"})
	}

	dbUser, err := utils.AuthenticateUser(db.(*gorm.DB), &user)
	if err != nil {
		return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error": "Invalid credentials"})
	}
	token, err := utils.CreateToken(dbUser, c.Locals("jwtSecret").([]byte))
	if err != nil {
		return c.SendStatus(fiber.StatusInternalServerError)
	}

	c.ClearCookie("authtoken")
	cookie := new(fiber.Cookie)
	cookie.Name = "authtoken"
	cookie.Value = token
	cookie.Expires = time.Now().Add(24 * time.Hour)
	c.Cookie(cookie)
	return c.JSON(fiber.Map{"token": token})
}

func AccessHandler(c *fiber.Ctx) error {
	return c.JSON(fiber.Map{"message": "Data accessed successfully"})
}
